package dk.hojlind.hackhunt.control;

import java.util.ArrayList;

import dk.hojlind.hackhunt.model.Advisory;
import dk.hojlind.hackhunt.model.ClientSocket;
import dk.hojlind.hackhunt.model.Observer;
import dk.hojlind.hackhunt.model.Subject;
import dk.hojlind.hackhunt.view.AdvisoryViewer;

public class AdvisoryHandler extends Handler implements Observer{

	//Public variables
	
	//Private variables
	ArrayList<Advisory> advisories;
	String advisoryCode = "advisory";
	
	public AdvisoryHandler()
	{
		advisories = new ArrayList<Advisory>();
	}
	
	public AdvisoryHandler(String adress, int port, Subject serverService) 
	{
			super(adress, port);
			advisories = new ArrayList<Advisory>();
			advisories.add(new Advisory("title", "affectedService", "description", "challenge-br-svar1 bla bla-br-svar2 bla blo-br-svar3 bla bli", "hint", 1, 1));
			serverService.registerObserver(this);
	}
	
	public void addAdvisory(String advisoryString)
	{
		String[] advisoryContent = advisoryString.split(";");
		
		Advisory advisory = new Advisory(advisoryContent[1], advisoryContent[2], advisoryContent[3], advisoryContent[4], advisoryContent[5], Integer.parseInt(advisoryContent[6].trim()));
		
		advisories.add(advisory);
	}
	
	public void deleteAdvisory()
	{
		
	}
	
	public ArrayList<String> getAdvisories()
	{
		ArrayList<String> advisoryTitles = new ArrayList<String>();
		
		for(int i = 0; i < advisories.size(); i++)
		{
			advisoryTitles.add(advisories.get(i).getTitle());
		}
		
		return advisoryTitles;
	}
	
	public void sendAdvisoryAnswer(int id, int correctLine, String patchExploit)
	{
		String message = "advisory" + ";" + id + ";" + correctLine + ";" + patchExploit + ";" + user + ";" + pass + ";" + ownAddress;
		socket = new ClientSocket(adress, port);
		result = socket.processRequest(message);
	}
	
	public boolean showAdvisoryByID(int advisoryID)
	{
		for(int i = 0; i < advisories.size(); i++)
		{
			if(advisoryID == advisories.get(i).getID())
			{
				showAdvisory(advisories.get(i));
				return true;
			}
		}
		return false;
	}
	
	public boolean showAdvisoryByIndex(int indexInArray)
	{
		showAdvisory(advisories.get(indexInArray));
		return true;
	}
	
	private void showAdvisory(Advisory advisoryToShow)
	{
		new AdvisoryViewer(advisoryToShow, this).setVisible(true);
	}

	@Override
	public void update(String message) 
	{
		if(message.contains(advisoryCode))
		{
			addAdvisory(message);
		}
	}

}
